<template>
  <van-popup v-model:show="visible" position="bottom" :style="{ height: '45%' }" round>
    <!-- 使用 Vant DatePicker 实现年月日时分选择 -->
    <van-date-picker v-model="selectedValues" :columns-type="['year', 'month', 'day', 'hour', 'minute']" title="选择出生时间"
      :min-date="minDate" :max-date="maxDate" @change="onPickerChange" @confirm="onPickerConfirm"
      @cancel="onPickerCancel" />
  </van-popup>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue'

// Props
interface Props {
  modelValue: boolean
  defaultDateTime?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  defaultDateTime: ''
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [datetime: string]
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 选中的值
const selectedValues = ref<string[]>([])

// 日期范围
const minDate = new Date(1950, 0, 1)
const maxDate = new Date(2050, 11, 31)

// 初始化状态
const isInitialized = ref(false)

// Picker 变化事件
const onPickerChange = (values: string[]) => {
  try {
    selectedValues.value = values
  } catch (error) {
    console.error('Picker change error:', error)
  }
}

// Picker 确认事件
const onPickerConfirm = (values: string[]) => {
  try {
    console.log('Picker confirm triggered:', values)
    selectedValues.value = values
    handleConfirm()
  } catch (error) {
    console.error('Picker confirm error:', error)
  }
}

// Picker 取消事件
const onPickerCancel = () => {
  try {
    handleCancel()
  } catch (error) {
    console.error('Picker cancel error:', error)
  }
}

// 处理确认
const handleConfirm = () => {
  try {
    console.log('Handle confirm called, selectedValues:', selectedValues.value)
    let datetimeText = ''

    if (selectedValues.value && selectedValues.value.length >= 5) {
      const [year, month, day, hour, minute] = selectedValues.value
      datetimeText = `${year}-${month}-${day} ${hour}:${minute}`
    } else if (selectedValues.value && selectedValues.value.length >= 3) {
      const [year, month, day] = selectedValues.value
      datetimeText = `${year}-${month}-${day}`
    }

    console.log('Emitting confirm with:', datetimeText)
    emit('confirm', datetimeText)
    console.log('Setting visible to false')
    visible.value = false
  } catch (error) {
    console.error('Handle confirm error:', error)
    visible.value = false
  }
}

// 处理取消
const handleCancel = () => {
  visible.value = false
}

// 监听弹窗显示，初始化默认值
watch(visible, async (newVal) => {
  if (newVal && !isInitialized.value) {
    await nextTick()
    // 初始化当前时间
    const now = new Date()
    const year = now.getFullYear().toString()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const hour = now.getHours().toString().padStart(2, '0')
    const minute = now.getMinutes().toString().padStart(2, '0')

    selectedValues.value = [year, month, day, hour, minute]
    isInitialized.value = true
  } else if (!newVal) {
    isInitialized.value = false
  }
}, { immediate: true })
</script>

<style scoped>
/* 使用 Vant 默认样式 */
</style>